package com.github.yangyishe.p200;

import com.github.yangyishe.ListNode;

/**
 * floyd算法解决, 是否有环形链表
 */
public class Problem141Floyd {
    public static void main(String[] args) {
        int[] arr=new int[]{3,2,0,-4};
        int pos=1;
        ListNode instance = ListNode.getInstance(arr, pos);

        Problem141 problem141 = new Problem141();
        boolean b = problem141.hasCycle(instance);
        System.out.println(b);
    }

    public boolean hasCycle(ListNode head){
        if (head==null) {
            return false;
        }
        ListNode slowNode=head;
        ListNode fastNode=head;

        int temp=0;
        while(fastNode!=null){
            fastNode=fastNode.next;
            temp++;

            if (temp>1) {
                temp=0;
                slowNode=slowNode.next;
            }

            if (fastNode==slowNode) {
                return true;
            }
        }

        return false;
    }
}
